package web.demo.service.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.List;

import web.demo.dao.impl.OrdersDao;
import web.demo.entity.OrderDetail;
import web.demo.entity.Orders;
import web.demo.factory.BeanFactory;
import web.demo.service.IOrdersService;
import web.demo.utils.JdbcUtils;

public class OrdersService implements IOrdersService{

	private OrdersDao ordersDao=BeanFactory.getInstance("ordersDao",OrdersDao.class);
	@Override
	public boolean addOrders(Orders orders) {
		return ordersDao.addOrders(orders);
	}

	@Override
	public List<Orders> getAll() {
		return ordersDao.getAll();
	}

	@Override
	public boolean update(Orders orders) {
		return ordersDao.update(orders);
	}

	@Override
	public boolean delete(int ordersId) {
		return ordersDao.delete(ordersId);
	}

	@Override
	public Orders getByDate(Date date) {
		return ordersDao.getByDate(date);
	}

	@Override
	public boolean addOrders(Orders orders, List<OrderDetail> orderDetailList) {
		//事务操作
		Connection conn=JdbcUtils.getConnection();
		PreparedStatement pstmt=null;
		Object[] ordersParams={
				orders.getFoodTable_id(),
				orders.getOrder_date(),
				orders.getTotal_price(),
				orders.getStatus()
		};
		String ordersSql="insert into orders (foodTable_id,order_date,total_price,status) values(?,?,?,?)";
		String orderDetailSql="insert into orderDetail (food_id,orders_id,food_count) values(?,?,?)";
		try {
			conn.setAutoCommit(false);
			pstmt=conn.prepareStatement(ordersSql,Statement.RETURN_GENERATED_KEYS);
			for(int i=0;i<ordersParams.length;i++){
				pstmt.setObject(i+1,ordersParams[i]);
			}
			//添加成功，返回自增长的order_id
			int ordersResult=pstmt.executeUpdate();
			//获取自增长的id值，给下面的订单详情表使用
			ResultSet order_ids=pstmt.getGeneratedKeys();
			order_ids.next();
			int order_id=order_ids.getInt(1);
			int orderDetailResult=0;
			if(ordersResult>0){
				pstmt=conn.prepareStatement(orderDetailSql);
				for(OrderDetail orderDetail:orderDetailList){
					Object[] orderDetailParams={
							orderDetail.getFood_id(),
							order_id,
							orderDetail.getFood_count()
					};
					for(int i=0;i<orderDetailParams.length;i++){
						pstmt.setObject(i+1, orderDetailParams[i]);
					}
					orderDetailResult+=pstmt.executeUpdate();
				}
			}
			conn.commit();
			if(ordersResult>0 && orderDetailResult>0){
				return true;
			}else{
				return false;
			}
		} catch (SQLException e) {
			try {
				conn.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}finally{
			if(conn!=null){
				try {
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return false;
	}

}
